package m202405.d11;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/11 11:55
 */
public class Q128 {


    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int max = 0;
        //这里如果遍历数组会慢
        //for(int num:nums){
        for (int num : set) {
            if (!set.contains(num - 1)) {
                int count = 1;
                int cNum = num;
                while (set.contains(cNum + 1)) {
                    count += 1;
                    cNum += 1;
                }
                max = Math.max(count, max);
            }
        }
        return max;
    }


    public int longestConsecutive1(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int max = 0;
        Set<Integer> rs = new HashSet<>();
        for (Integer integer : set) {
            if (rs.contains(integer)) {
                continue;
            }
            rs.clear();
            find(integer, set, rs);
            max = Math.max(rs.size(), max);
        }
        return max;
    }

    private void find(int i, Set<Integer> nums, Set<Integer> rs) {
        while (nums.contains(i)) {
            rs.add(i);
            i++;
        }
        while (nums.contains(i)) {
            rs.add(i);
            i--;
        }
    }
}
